function varargout = TLGainDlg(action,varargin)

% TL_GAIN_DLG manages user interface for TargetLink Gain block
%
% SYNTAX dlgInfo = TLGainDlg('GetDlgInfo');
%   gets dialog info of TargetLink Gain block
%
%   INPUT ARGUMENTS
%   -/-      
%
%   OUTPUT ARGUMENTS
%   dlgInfo     dialog information contains pageNames etc.
%
% SYNTAX [sheetDims, ctrlPos] = TLGainDlg('CtrlPositions', pageName, commonGeom, dlgInfo, sheetDims);
%   calculates the control positions of all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   commonGeom      common geometry data
%   dlgInfo         dialog information contains pageNames etc.
%   sheetDims       dimension of sheet
%
%   OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% SYNTAX dlgdata = TLGainDlg('Create', pageName, dlgfig, dlgdata);
%   creates all controls of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX [dlgdata,bModified] = TLGainDlg('Manage', pageName, dlgfig, dlgdata, pageAction);
%   manages all actions of dialog page: <pageName>
%
%   INPUT ARGUMENTS
%   pageName        name of current page
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageAction      modified control of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%   bModified       flag = 1, if dialog data are modified, =0 otherwise
%
% SYNTAX dlgdata = TLGainDlg('Update', dlgfig, dlgdata, pageNum);
%   updates all controls of dialog page: <pageNum>
%
%   INPUT ARGUMENTS
%   dlgfig          figure handle
%   dlgdata         dialog data
%   pageNum         number of current page
%
%   OUTPUT ARGUMENTS
%   dlgdata         modified dialog data
%
% SYNTAX TLGainDlg('Apply', dlgfig, dlgdata);
%   writes current blockdata to block and DD
%
%   INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
%   OUTPUT ARGUMENTS
%   - / -


% Author(s): D. Andoleit, T. Pietzsch
% $RCSfile: TLGainDlg.m $
% $ProjectName: e:/ARC/Components/HostSW/SimulinkBlocksets/TLBlocksets/CommonBlockset/CommonBlockset_SimBlocksUI/Sources/MSrc/project.pj $
% $Revision: 1.17 $
% $Date: 2011/07/21 13:12:14MESZ $
%
% Copyright ?2011 dSPACE GmbH. All rights reserved.


switch action
    case 'GetDlgInfo'
        hBlock = varargin{1};
        dlgInfo = tl_get_dlginfodefaults('tlsim');
        titleName = 'Gain';
        pathinfo = tl_pathinfo(hBlock);
        dlgInfo.title = sprintf('TargetLink %s: %s', titleName, pathinfo.shortDisplayName);
        dlgInfo.pageNames = {
            'Output', ...
            'Gain', ...
            'Logging & Autoscaling', ...
            'Documentation'};
        varargout{1} = dlgInfo;
        varargout{2} = get_tlcg_data(hBlock);

    case 'CtrlPositions'
        pageName     = varargin{1};
        commonGeom   = varargin{2};
        sheetDims    = varargin{4};
        switch pageName
            case 'Output'
                excludedCtrls = {'inheritproperties'};
                [sheetDims, ctrlPos] = ...
                    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

            case 'Gain'
                [sheetDims, ctrlPos] = FcnCalcGainControlPositions(commonGeom);

            case 'Logging & Autoscaling'
                excludedCtrls = {};
                [sheetDims, ctrlPos] = ...
                    TLManageLoggingCtrls('calcCtrls', commonGeom, sheetDims, excludedCtrls);

            case 'Documentation'
                bTblBlock = 0;
                bCodeComment = 1;
                [sheetDims,ctrlPos] = TLManageDocCtrls( ...
                    'ctrlpos', commonGeom, sheetDims, bCodeComment, bTblBlock);
        end
        varargout{1} = sheetDims;
        varargout{2} = ctrlPos;
        
    case 'Create'
        pageName = varargin{1};
        dlgfig   = varargin{2};
        dlgdata  = varargin{3};
        pageNum  = strmatch(pageName, dlgdata.pageNames, 'exact');
        switch pageName
            case 'Output'
                % create all controls
                dlgdata = TLManageVariableCtrls( ...
                    'create', pageNum, dlgfig, dlgdata);
                dlgdata = TLManageScalingCtrls( ...
                    'create', pageNum, dlgfig, dlgdata);

            case 'Gain'
                dlgdata = FcnCreateGainControls(pageNum,dlgfig,dlgdata);

            case 'Logging & Autoscaling'
                dlgdata = ...
                    TLManageLoggingCtrls('create',pageNum,dlgfig,dlgdata);

            case 'Documentation'
                dlgdata = ...
                    TLManageDocCtrls('create',pageNum,dlgfig,dlgdata);
        end
        dlgdata.pageData{pageNum}.ctrlPos = [];
        varargout{1} = dlgdata;

    case 'Manage'
        pageName   = varargin{1};
        dlgfig     = varargin{2};
        dlgdata    = varargin{3};
        pageAction = varargin{4};
        pageNum    = strmatch(pageName,dlgdata.pageNames,'exact');
        % special handling of view code on gain tab
        if strcmp(pageAction, 'ViewCode') && pageNum ~= 2
            pageName = 'Output';
        end

        switch pageName
            case 'Output'
                [dlgdata, bModified1] = ...
                    TLManageVariableCtrls('manage', pageNum, dlgfig, ...
                    dlgdata, pageAction, 'output');
                [dlgdata, bModified2] = ...
                    TLManageScalingCtrls('manage', pageNum, dlgfig, ...
                    dlgdata, pageAction, 'output');

                bModified = bModified1 || bModified2;

            case 'Gain'
                [dlgdata, bModified] = ...
                    FcnManageGainControls(pageNum,dlgfig,dlgdata,pageAction);

            case 'Logging & Autoscaling'
                [dlgdata, bModified] = ...
                    TLManageLoggingCtrls('manage', pageNum, dlgdata, pageAction, 'logdata');

            case 'Documentation'
                [dlgdata, bModified] = ...
                    TLManageDocCtrls('callback', pageNum, dlgfig, ...
                    dlgdata, pageAction);
        end
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'ManageSystemIcons',
        dlgfig     = varargin{1};
        dlgdata    = varargin{2};
        pageAction = varargin{3};
        [dlgdata, bModified] = FcnManageSystemIcons(dlgfig,dlgdata,pageAction);
        varargout{1} = dlgdata;
        varargout{2} = bModified;

    case 'Update'
        dlgfig    = varargin{1};
        dlgdata   = varargin{2};
        pageNum   = varargin{3};

        pageName  = dlgdata.pageNames{pageNum};

        switch pageName
            case 'Output'
                % update all controls
                dlgdata = TLManageVariableCtrls( ...
                    'update', pageNum, dlgdata, 'output');
                dlgdata = TLManageScalingCtrls( ...
                    'update', pageNum, dlgdata, 'output', []);

                % set controls
                TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
                TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);

            case 'Gain'
                dlgdata = FcnUpdateGainControls(dlgdata, dlgfig, pageNum);

            case 'Logging & Autoscaling'
                dlgdata =  TLManageLoggingCtrls('update',pageNum,dlgdata,'logdata','output');
                TLManageLoggingCtrls('setCtrls',pageNum, dlgfig, dlgdata);

            case 'Documentation'
                TLManageDocCtrls('update', pageNum, dlgfig, dlgdata);
        end
        varargout{1} = dlgdata;

    case 'Apply'
        dlgdata  = varargin{2};
        bClose   = varargin{3};
        [dlgdata, bClose] = tl_apply_blockdata(dlgdata, bClose);
        varargout{1} = dlgdata;
        varargout{2} = bClose;

    otherwise
        error(['Invalid action: "' action '"']);
end


%-----------------------------------------------------------------------------------------
% FcnManageSystemIcons manage actions of toolbar icons
%
% INPUT ARGUMENTS
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   action      action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageSystemIcons(dlgfig, dlgdata, action) %#ok

bModified = false;
switch action
    case 'EditCode'
        % look for associated production code file
        [codefile,blockstr] = get_codefile(dlgdata.model);
        if ~isempty(codefile)
            codeedit(codefile,blockstr);
        end

    case 'ViewCode'
        switch dlgdata.pageNames{dlgdata.CurrentPageNum}
            case 'Gain'
                blockVar = 'gain';
                tl_create_links_to_model('ShowDeclaration',dlgdata.model, blockVar);
            otherwise
                blockVar = 'output';
                tl_create_links_to_model('ShowComputation',dlgdata.model, blockVar);
        end

    otherwise
        error('Invalid callback');

end % switch(action)


%-----------------------------------------------------------------------------------------
% FcnCalcGainControlPositions calculates positions for all controls on gain page
%
% INPUT ARGUMENTS
%   commonGeom      common geometrie information
%
% OUTPUT ARGUMENTS
%   sheetDims       modified dimension of sheet
%   ctrlPos         positions of controls
%
% HINT:
% Positions are calculated from the bottom left of the figure to avoid
% dependencies on figure size
%-----------------------------------------------------------------------------------------
function [sheetDims, ctrlPos] = FcnCalcGainControlPositions(commonGeom)

excludedCtrls = {'calcranges', 'saturate', 'inheritproperties'};
[sheetDims, ctrlPos, col, colDelta, rowDelta] = ...
    tl_calc_ctrls_positions(commonGeom, excludedCtrls);

strings_and_styles = { ...
    'Gain:',         'text'; ...
    'Tolerance',     'text'; ...
    '  %',           'text'; ...
    'Scalar',        'checkbox'; ...
    'Use value of Data Dictionary variable',    'checkbox'};

[valLabelSize, ...
    toleranceLabelSize, ...
    toleranceUnitLabelSize, ...
    scalarCheckboxSize, ...
    useDDValueCheckboxSize] = ...
    ds_get_uicontrol_sizes(commonGeom, strings_and_styles);

% define new height for addoptGroupbox
ctrlPos.addoptGroupbox(4) = commonGeom.editHeight ...
    + commonGeom.checkboxHeight ...
    + 2*rowDelta ...
    + commonGeom.frameBottomEdgeBuffer ...
    + commonGeom.frameTopEdgeBuffer;

%---------------------------------------
% 2nd row
cy = commonGeom.frameBottomEdgeBuffer;

% ddv checkbox
cx = col(2);
ctrlPos.useDDValueCheckbox = [cx, cy, useDDValueCheckboxSize];

%---------------------------------------
% 1st row
cy = cy + commonGeom.editHeight + rowDelta;

% gain value label
cx = col(1);
ctrlPos.valLabel = [cx cy valLabelSize];

% gain value edit
cx = col(2);
ctrlPos.valEdit = [cx cy ctrlPos.varEdit(3:4)];

% tolerance label
cx = col(6) - colDelta/3 - toleranceLabelSize(1);
ctrlPos.toleranceLabel = [cx cy toleranceLabelSize];

% tolerance edit
cx = col(6);
ctrlPos.toleranceEdit = [cx cy ctrlPos.widthEdit(3:4)];

% tolerance unit
cx = cx + ctrlPos.toleranceEdit(3);
ctrlPos.toleranceUnitLabel = [cx cy toleranceUnitLabelSize];

% scalar checkbox
cx = cx + ctrlPos.toleranceUnitLabel(3) + colDelta;
ctrlPos.scalarCheckbox = [cx cy scalarCheckboxSize];

% increase sheet dimensions
sheetDims(2) = sheetDims(2) + ...
    + ctrlPos.addoptGroupbox(4) ...
    + commonGeom.textHeight;


%-----------------------------------------------------------------------------------------
% FcnCreateOutputPage creates the figure window
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnCreateGainControls(pageNum,dlgfig,dlgdata)

Children = dlgdata.pageData{pageNum}.children;
ctrlPos  = dlgdata.pageData{pageNum}.ctrlPos;
pageName = dlgdata.pageNames{pageNum};
% create the addoptGroupbox which will contain gain value
Children.addoptGroupbox = uipanel( ...
    'Parent',            dlgfig, ...
    'Title',            {'Gain value'}, ...
    'Units',            'pixels', ...
    'Position',          ctrlPos.addoptGroupbox);

% tolerance controls
Children.toleranceLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Tolerance:', ...
    'Position',           ctrlPos.toleranceLabel);

Children.toleranceEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.toleranceEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''toleranceEdit'')',pageName));

Children.toleranceUnitLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             ' %', ...
    'Position',           ctrlPos.toleranceUnitLabel);

% value controls
Children.valLabel = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'text', ...
    'String',             'Gain:', ...
    'Position',           ctrlPos.valLabel);

Children.valEdit = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'BackgroundColor',    'w', ...
    'Style',              'edit', ...
    'Position',           ctrlPos.valEdit, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''valEdit'')',pageName));

Children.scalarCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Scalar', ...
    'Position',           ctrlPos.scalarCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''scalarCheckbox'')',pageName));

Children.useDDValueCheckbox = uicontrol( ...
    'Parent',             Children.addoptGroupbox, ...
    'Style',              'checkbox', ...
    'String',             'Use value of Data Dictionary variable', ...
    'Position',           ctrlPos.useDDValueCheckbox, ...
    'Callback',           sprintf('tldlg(''%s'',gcbf,''useDDValueCheckbox'')',pageName));

dlgdata.extdata.gain.currentElement = 1;

dlgdata.pageData{pageNum}.children = Children;

% invoke standard function to create production code options controls
dlgdata = TLManageVariableCtrls('create',pageNum,dlgfig,dlgdata);
dlgdata = TLManageScalingCtrls('create',pageNum,dlgfig,dlgdata);


%-----------------------------------------------------------------------------------------
% FcnManageGainControls manage control actions of gain page
%
% INPUT ARGUMENTS
%   pageNum     number of current page
%   dlgfig      handle for dialog figure
%   dlgdata     dialog data
%   pageAction  action at one control of current page
%
% OUTPUT ARGUMENTS
%   dlgdata     modified dialog data
%   bModified   flag = 1, if dialog data are modified, =0 otherwise
%-----------------------------------------------------------------------------------------
function [dlgdata, bModified] = FcnManageGainControls(pageNum,dlgfig,dlgdata,pageAction)

Children   = dlgdata.pageData{pageNum}.children;

switch pageAction
    case 'valEdit'
        gainstr = deblank(get(Children.valEdit, 'String'));
        if ~isempty(gainstr)
            if strcmp(gainstr, 'ddv')
                if isempty(dlgdata.data.gain.variable)
                    beep;
                else
                    dlgdata.data.gain.value = ['ddv(''', dlgdata.data.gain.variable, ''')'];
                    dlgdata.data.gain.useddvariablevalue = true;
                end
            else
                dlgdata.data.gain.value = gainstr;
            end
        else
            beep;
        end
        bModified = true;

    case 'toleranceEdit'
        tolerance = str2double(get(Children.toleranceEdit, 'String'));
        if ~isnan(tolerance) && numel(tolerance) == 1 && tolerance >= 0
            dlgdata.data.gain.tolerance = real(tolerance);
        else
            beep;
        end
        bModified = true;

    case 'ViewCode'
        tl_create_links_to_model('ShowDeclaration',dlgdata.model, 'gain');
        bModified = false;

    case 'scalarCheckbox'
        dlgdata.data.gain.scalar = get(Children.scalarCheckbox, 'Value');
        bModified = true;

        case 'useDDValueCheckbox'
        if get(Children.useDDValueCheckbox, 'Value')
            dlgdata.data.gain.value = ['ddv(''', dlgdata.data.gain.variable, ''')'];
            dlgdata.data.gain.useddvariablevalue = true;
        else
            dlgdata.data.gain.useddvariablevalue = false;
        end
        bModified = true;

    otherwise
        [dlgdata, bModified1] = TLManageVariableCtrls('manage', ...
            pageNum, dlgfig, dlgdata, pageAction, 'gain');
        [dlgdata, bModified2] = TLManageScalingCtrls('manage', ...
            pageNum, dlgfig, dlgdata, pageAction, 'gain');
        bModified = bModified1 || bModified2;
end


%-----------------------------------------------------------------------------------------
% FcnUpdateGainControls updates the controls of the gain tab
%
% INPUT ARGUMENTS
%   dlgdata     dialog data
%   dlgfig      figure handle of dialog
%   pageNum     page Number
%
% OUTPUT ARGUMENTS
%   dlgdata     dialog data
%-----------------------------------------------------------------------------------------
function dlgdata = FcnUpdateGainControls(dlgdata, dlgfig, pageNum)

Children = dlgdata.pageData{pageNum}.children;

% default control status for controls of gain value groupbox
valEditCtrlStatus            = struct('enable', 'on');
toleranceEditCtrlStatus      = struct('enable', 'on' , 'string', '');
toleranceUnitLabelCtrlStatus = struct('enable', 'on');
scalarCheckboxCtrlStatus     = struct('enable', 'on', 'value', 0);

% if class is default, scalar can not be selected and has no effect
if strcmp(tl_deblank(dlgdata.data.gain.class,2), 'default')
    dlgdata.data.gain.scalar = 0;
    scalarCheckboxCtrlStatus.enable = 'off';
end

% if scalar is selected, scalar Expansion Flag is selected as well (is later disabled)
if dlgdata.data.gain.scalar
    dlgdata.extdata.gain.scalarExp = 1;
end

% invoke standard update methods
dlgdata = TLManageVariableCtrls('update', pageNum, dlgdata, 'gain');
[gain, constraint, bCompliant] = tl_get_param_constraints(dlgdata.data.gain, dlgdata.extdata.gain);
dlgdata = TLManageScalingCtrls('update', pageNum, dlgdata, 'gain', constraint);

% status of ddv checkbox
useDDValueCheckboxCtrlStatus.enable = flag2str(~isempty(dlgdata.data.gain.variable));
useDDValueCheckboxCtrlStatus.value = dlgdata.data.gain.useddvariablevalue;

valEditCtrlStatus.string = dlgdata.data.gain.value;
if dlgdata.data.gain.useddvariablevalue
    valEditCtrlStatus.enable = 'inactive';
end
if ~bCompliant
    valEditCtrlStatus.iserror = 1;
end

% for parameters there are no simulated ranges. Instead, write min/max of gain value
simulatedLabelCtrlStatus = tl_get_control_userdata(Children.simulatedLabel);
upperSimulatedValueCtrlStatus = tl_get_control_userdata(Children.upperSimulatedValue);
lowerSimulatedValueCtrlStatus = tl_get_control_userdata(Children.lowerSimulatedValue);
if dlgdata.extdata.gain.scalarExp
    simulatedLabelCtrlStatus.string = 'of gain';
else
    simulatedLabelCtrlStatus.string = 'of element';
end

scalarExpCheckboxCtrlStatus = tl_get_control_userdata(Children.scalarExpCheckbox);
toleranceEditCtrlStatus.string = dlgdata.data.gain.tolerance;
scalarCheckboxCtrlStatus.value = dlgdata.data.gain.scalar;
% if scalar is selected, scalar Expansion Flag is selected as well and must be disabled
if dlgdata.data.gain.scalar
    scalarExpCheckboxCtrlStatus.enable = 'off';
end


% check and set status of gain value groupbox controls and the min/max of the
% gain value
if ~strcmp(tl_deblank(dlgdata.data.gain.class,2), 'default')
    % class is not default: disable tolerance controls
    toleranceEditCtrlStatus.enable = 'off';
    toleranceUnitLabelCtrlStatus.enable = 'off';
    % fill row with simulated values
end

% write back control status of extra controls to the controls'
% UserData property
extraCtrlsList = {
    'toleranceEdit' ...
    'toleranceUnitLabel' ...
    'valEdit' ...
    'scalarCheckbox' ...
    'useDDValueCheckbox'};
standardCtrlsList = {
    'simulatedLabel' ...
    'upperSimulatedValue' ...
    'lowerSimulatedValue' ...
    'scalarExpCheckbox'}; ...
    ctrlsList = [extraCtrlsList standardCtrlsList];
for ctrlsNo=1:length(ctrlsList)
    ctrl = Children.(ctrlsList{ctrlsNo});
    UserData = get(ctrl, 'UserData');
    UserData.ctrlStatus = eval([ctrlsList{ctrlsNo} 'CtrlStatus']);
    set(ctrl, 'UserData', UserData);
end

% set control status of variable, scaling and gain parameter groupbox controls
TLManageVariableCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLManageScalingCtrls('setCtrls', pageNum, dlgfig, dlgdata);
TLSetCtrlsStatus(dlgfig,Children, extraCtrlsList)
